﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Newtonsoft.Json;
using T163.Open.Api.WP7.Model;
using T163.Open.Api.WP7.Sample.Utility;
using System.Diagnostics;

namespace T163.Open.Api.WP7.Sample
{
    public partial class MainPage : PhoneApplicationPage
    {
        private OAuthService oauth;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (!OAuthClientHelper.IsAuthorized())
            {
                App.ClickCount += 1;
                if (App.ClickCount >= 3)
                    return;

                NavigationService.Navigate(new Uri("/AuthorizePage.xaml", UriKind.Relative));
            }
            else
            {
                var entry = NavigationService.BackStack.FirstOrDefault();
                if (entry != null && entry.Source.OriginalString.Contains("AuthorizePage"))
                    NavigationService.RemoveBackEntry();

                if (oauth == null)
                    oauth = new OAuthService(App.Consumer, App.AccessToken);

                oauth.GetPublicTimeLine(response =>
                    {
                        if (response.IsSuccess && !string.IsNullOrWhiteSpace(response.ResponseText))
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                lbStatues.DataContext = JsonConvert.DeserializeObject<List<Statues>>(response.ResponseText);
                            });
                        }
                    }, null);
            }
        }

        private void btnStatues_Click(object sender, RoutedEventArgs e)
        {
            oauth.Update(response =>
                {
                    if (response.IsSuccess && !string.IsNullOrWhiteSpace(response.ResponseText))
                    {
                        
                    }
                }, null, new Statues { Text = txtStatues.Text });
        }

        private void btnCamera_Click(object sender, RoutedEventArgs e)
        {
            PhotoChooserTask pcTask = new PhotoChooserTask();
            pcTask.Completed += new EventHandler<PhotoResult>(pcTask_Completed);
            pcTask.Show();            
        }

        void pcTask_Completed(object sender, PhotoResult e)
        {
            if (e.TaskResult == TaskResult.OK)
            {
                byte[] image = ReadToEnd(e.ChosenPhoto);

                oauth.Upload(response =>
                {
                    if (response.IsSuccess && !string.IsNullOrWhiteSpace(response.ResponseText))
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                MessageBox.Show("success");
                            });
                    }
                }, null, e.OriginalFileName, image, txtStatues.Text);
            }
        }

        private byte[] ReadToEnd(System.IO.Stream stream)
        {
            long originalPosition = stream.Position;
            stream.Position = 0;

            try
            {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                byte[] buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }
                return buffer;
            }
            finally
            {
                stream.Position = originalPosition;
            }
        }
    }
}